package bsc.war.handler;

import bsc.ejb.entity.Attachment;
import bsc.ejb.entity.ColorimetrySettings;
import bsc.ejb.entity.Note;
import bsc.ejb.entity.ScoreCard;
import bsc.ejb.metadata.Colorimetry;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.model.ActionPlanPojo;
import bsc.war.model.Score;
import bsc.war.service.ScoreCardUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author Memo
 */
public class DashboardScoreCard extends AbstractController {

    public DashboardScoreCard() {
    }

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");

            processRequestInternal(request, response, delegate);

        } catch (Exception e) {
            logger.error("Catched exception", e);
        }
        return new ModelAndView("dashboardScoreCard");
    }

    public static void processRequestInternal(HttpServletRequest request,
            HttpServletResponse response, DelegateBSC delegate) {

        Date startDate = null;
        Date endDate = null;

        //Impresion de parametros


        //Get dats from calendars
        if (request.getParameter("startDate") != null && request.getParameter("endDate") != null) {
            Integer tmpDate[] = new Integer[3];
            StringTokenizer dateTokens = new StringTokenizer(request.getParameter("startDate"), "/");
            for (int i = 0; i < 3; i++) {
                tmpDate[i] = Integer.parseInt(dateTokens.nextToken());
            }

            Integer tmpDateFinal[] = new Integer[3];
            StringTokenizer dateTokensFinal = new StringTokenizer(request.getParameter("endDate"), "/");
            for (int i = 0; i < 3; i++) {
                tmpDateFinal[i] = Integer.parseInt(dateTokensFinal.nextToken());
            }

            startDate = ScoreCardUtils.generateDate(tmpDate[0], tmpDate[1], tmpDate[2]);
            endDate = ScoreCardUtils.generateDate(tmpDateFinal[0], tmpDateFinal[1], tmpDateFinal[2]);

        } else {

            startDate = ScoreCardUtils.generateMinimumDate(ScoreCardUtils.getSystemDate(request), 5);
            endDate = ScoreCardUtils.getSystemDate(request);
        }


        //Find the scorecards
        Long idScoreCard = Long.parseLong(request.getParameter("scoreCard"));
        ScoreCard scoreCard = delegate.findScoreCard(idScoreCard);



        //Define range of dates
        // List<Date> rangeDates = ScoreCardUtils.generateDates(ScoreCardUtils.getSystemDate(request));
        List<Date> rangeDates = ScoreCardUtils.generateDatesRange(startDate, endDate);

        Map<Date, Double> scoreCardScore = new HashMap<Date, Double>();
        Map<Date, String> scoreCardColor = new HashMap<Date, String>();
        Map<Note, List<Attachment>> noteAttachments = new HashMap<Note, List<Attachment>>();

        for (Date date : rangeDates) {
            //Calculate score for each date of the ScoreCard
            Score score = ScoreCardUtils.calculateScore(delegate, ScoreCardUtils.getSystemComparation(request), scoreCard, date);

            Colorimetry colorimetry = delegate.findColorimetry(scoreCard, score.getScore());

            scoreCardScore.put(date, score.getScore());
            scoreCardColor.put(date, colorimetry == null ? "" : colorimetry.getColor());
        }
        List<Note> notes = delegate.findNote(scoreCard);

        for (Note note : notes) {
            List<Attachment> attachments = delegate.findAttachment(note);
            noteAttachments.put(note, attachments);
        }

        //Se sube la colorimetría

        List<ColorimetrySettings> colorimetries = delegate.findColorimetrySettings(scoreCard);
        Map<ColorimetrySettings, Double> colorRangeMin = new HashMap<ColorimetrySettings, Double>();
        Map<ColorimetrySettings, Double> colorRangeMax = new HashMap<ColorimetrySettings, Double>();
        for (ColorimetrySettings colorimetrySettings : colorimetries) {
            Double maxScore = colorimetrySettings.getMaxScore();
            Double minScore = colorimetrySettings.getMinScore();

            colorRangeMax.put(colorimetrySettings, maxScore);
            colorRangeMin.put(colorimetrySettings, minScore);
        }


        //ActionPlans
        List<ActionPlanPojo> actionPlanPojos = ScoreCardUtils.getActionPlans(delegate, scoreCard);
        request.setAttribute("actionPlanPojos", actionPlanPojos);

        request.setAttribute("scoreCard", scoreCard);
        request.setAttribute("rangeDates", rangeDates);
        request.setAttribute("scoreCardScore", scoreCardScore);
        request.setAttribute("scoreCardColor", scoreCardColor);
        request.setAttribute("notes", notes);
        request.setAttribute("noteAttachments", noteAttachments);

        request.setAttribute("startDate", startDate);
        request.setAttribute("endDate", endDate);


        //Colores
        request.setAttribute("colorimetries", colorimetries);
        request.setAttribute("colorRangeMin", colorRangeMin);
        request.setAttribute("colorRangeMax", colorRangeMax);


    }
}
